package com.heimachefu.module.resource.service.impl;

import com.heimachefu.common.CommonUtils;
import com.heimachefu.common.Result;
import com.heimachefu.module.resource.check.ResourceParam;
import com.heimachefu.module.resource.dao.ResourceRepository;
import com.heimachefu.module.resource.entity.ResourceEntity;
import com.heimachefu.module.resource.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * @author liuxingdong@heimachefu.com
 * @date 2019/7/19 16:17
 */
@Service
public class ResourceServiceImpl implements ResourceService{


    private final ResourceRepository resourceRepository;

    @Autowired
    public ResourceServiceImpl(ResourceRepository resourceRepository) {
        this.resourceRepository = resourceRepository;
    }

    @Override
    public List<ResourceEntity> getChildResourceList(List<ResourceEntity> resourceEntities) {
        if(resourceEntities != null &&! resourceEntities.isEmpty()){
            for (ResourceEntity resourceEntity:resourceEntities
                 ) {
                List<ResourceEntity> resourceEntityList = resourceRepository.findByParentResourceId(resourceEntity.getResourceId());
                if(resourceEntityList != null && !resourceEntityList.isEmpty()){
                    resourceEntity.setChildResource(resourceEntityList);
                    getChildResourceList(resourceEntityList);
                }
            }
        }
        return resourceEntities;
    }

    @Override
    public Result saveResource(ResourceEntity resourceEntity) {
        ResourceEntity resourceEntity1 =  resourceRepository.save(resourceEntity);
        return CommonUtils.success(null);
    }

    @Override
    public Page<ResourceEntity> list(Integer pageNo, Integer pageSize) {
        Pageable pageable =  PageRequest.of(pageNo, pageSize); //页码：前端从1开始，jpa从0开始，做个转换
        return resourceRepository.findAll(pageable);
    }
}
